package com.kuding.config.conditional;

import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import com.kuding.enums.WhatDoWeHave;

public class ComponentEnabledConditional extends SpringBootCondition {

	private static final String PREFIX = "vinus.aliyun";

	private static final String SUFFIX = "enabled";

	private static final String CLASSNAME = ConditionalOnEnableAliyun.class.getName();

	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		var annoAttr = metadata.getAnnotationAttributes(CLASSNAME);
		var doWeHave = annoAttr.get("value");
		var propName = format((WhatDoWeHave) annoAttr.get("value"));
		var enabled = context.getEnvironment().getProperty(propName, Boolean.class, false);
		return enabled ? ConditionOutcome.match(doWeHave + " is enbaled")
				: ConditionOutcome.noMatch(doWeHave + " is not enabled");
	}

	private final String format(WhatDoWeHave doWeHave) {
		return String.format("%s.%s.%s", PREFIX, doWeHave.getValue(), SUFFIX);
	}

}
